using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using mvcincode.Models;

namespace mvcincode.Controllers;

public class AccountController : Controller
{
    public IActionResult Login() => View();

    [HttpPost]
    public async Task<IActionResult> Login(Account account)
    {
        if (!ModelState.IsValid)
            return View();

        // TODO: 这里写登录验证比对数据库中的用户名和密码的代码,判断是否是有效用户

        var adminClaims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, account.Username),
            new Claim(ClaimTypes.Role, "Admin"),
        };
        // 注意:这里一定要加上第二个参数AuthenticationType,否则报错
        var adminIdentity = new ClaimsIdentity(adminClaims, CookieAuthenticationDefaults.AuthenticationScheme);
        var userPrincipal = new ClaimsPrincipal(new[] { adminIdentity });

        // 注意: Controller里面可以直接使用HttpContext, 不需要额外注册HttpContextAccessor
        await HttpContext.SignInAsync(userPrincipal);

        return Redirect("/Home/Privacy");
    }

    [HttpGet]
    public string GetJwtToken()
    {
        var claims = new []
        {
            new Claim(ClaimTypes.Name, "Alan"),
            new Claim(ClaimTypes.Role, "Admin")
        };

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtConstant.SECURITY_KEY));
        var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
        var jwtToken = new JwtSecurityToken(JwtConstant.ISSUER
            , JwtConstant.AUDIENCE
            , claims
            , null
            , DateTime.UtcNow.AddMinutes(JwtConstant.ACCESS_EXPIRATION)
            , credentials);
        var token = new JwtSecurityTokenHandler().WriteToken(jwtToken);

        return token;
    }
}
